//
//  LHSearchController.m
//  Project_B
//
//  Created by dllo on 15/12/30.
//  Copyright © 2015年 ZY. All rights reserved.
//

#import "LHSearchController.h"
#import "ZYDetailWebViewController.h"


@interface LHSearchController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate,LHSearchCellDelegate>
@property (nonatomic, retain) UISearchBar *searchBar; /**< 搜索框 */
@property (nonatomic, retain) UIButton *cancelButton; /**< 取消按钮 */
@property (nonatomic, retain) NSMutableArray *hotSearchArr; /**< 热词搜索数组 */
@property (nonatomic, retain) UITableView *tableView; /**< TableView */
@property (nonatomic, retain) NSMutableArray *searchDataArr; /**< 搜索数据数组 */
@property (nonatomic, retain) UITableView *searchTableView; /**< 搜索结果TableView */
@end

@implementation LHSearchController

- (void)viewDidAppear:(BOOL)animated
{
    ;
    self.navigationItem.title = @"搜索";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self searchHandleData];
    [self creatCancelButton];
    [self creatSearch];
    [self creatTableView];
    [self creatSearchTableView];
}
#pragma mark- 搜索热门
-(void)searchHandleData
{
    
    // AFN解析热词
//    [AFNetHandle GETWithURL:@"http://c.3g.163.com/nc/search/hotWord.html" body:nil httpHead:nil responseStyle:JSON success:^(id result) {
    [ZYTools getUrl:@"http://c.3g.163.com/nc/search/hotWord.html" body:nil result:ZYJSON headerFile:nil success:^(id result) {
        
        // 将搜索结果存入数组
        NSArray *tempArr = [result objectForKey:@"hotWordList"];
        
        // 初始化数组
        self.hotSearchArr = [NSMutableArray array];
        
        // 遍历数组
        for (NSDictionary *dic in tempArr) {
            
            // 初始化
            LHHotSearchModel *model = [[LHHotSearchModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            // 添加进热词搜索数组
            [self.hotSearchArr addObject:model];

        }
        
        // 重载界面
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];

}

#pragma mark ** 搜索解析
-(void)handleData
{
    
    // 拼接搜索字符串
    NSString *str = [self.searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet capitalizedLetterCharacterSet]];
    
    // 拼接网址
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/search/comp/MA==/20/%@.html?deviceId=MjY5NTJBNDEtMDIxMC00QjIxLUEwMTItMzFBRDk5REU2MDU0&version=NS4zLjQ=&channel=5aS05p2h", str];
    
    
    // AFNGET解析
     [ZYTools getUrl:url body:nil result:ZYJSON headerFile:nil success:^(id result) {
        
        // 取出数据存入字典
        NSDictionary *dic = [result objectForKey:@"doc"];
        
        // 取出数据存入数组
        NSArray *tempArr = [dic objectForKey:@"result"];
        
        // 搜索结果数组初始化
        self.searchDataArr = [NSMutableArray array];
        
        // 遍历数组
        for (NSDictionary *dicc in tempArr) {
            
            // 初始化
            LHSearchModel *model = [[LHSearchModel alloc] init];
            [model setValuesForKeysWithDictionary:dicc];
            // 将Model添加至搜索结果数组
            [self.searchDataArr addObject:model];
            
            // 过滤掉有声模块
            if ([model.title hasPrefix:@"【<em>有声</em>】"]) {
                [self.searchDataArr removeObject:model];
            }
            

        }
        
        // 重载界面
        [self.searchTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
    
    
}
-(void)creatSearch
{
    
    // 初始化
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 20, 64, SCREEN_WIDTH - SCREEN_WIDTH / 5, SCREEN_WIDTH / 10)];
    
    // 默认文字
    self.searchBar.placeholder = @"搜索";
    
    // 样式
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    // 协议
    self.searchBar.delegate = self;
    
    // 添加并并释放
    [self.view addSubview:self.searchBar];

    
}
-(void)creatCancelButton
{
    
    // 创建
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    // 标题
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    
    // 大小坐标
    self.cancelButton.frame = CGRectMake(SCREEN_WIDTH / 1.25, 64, SCREEN_WIDTH / 5, SCREEN_WIDTH / 10);
    
    // 方法
    [self.cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchUpInside];
    
    // 添加到视图上
    [self.view addSubview:self.cancelButton];
    
    
}
#pragma mark- 取消按钮响应方法
-(void)cancelButton:(UIButton *)cancelButton
{
    
    // 返回
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
}
#pragma mark- 创建搜索结果TableView
-(void)creatSearchTableView
{
    
    // 初始化
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 20 + SCREEN_WIDTH / 10 + 64, SCREEN_WIDTH, SCREEN_HEIGHT - 75 * ADAPT_HEIGHT) style:UITableViewStylePlain];
    
    // Tag值
    self.searchTableView.tag = 100001;
    
    // 协议
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    
    // footer初始化
    self.searchTableView.tableFooterView = [[UIView alloc] init];
    
    // 添加
    [self.view addSubview:self.searchTableView];
}
#pragma mark- 创建TableView
-(void)creatTableView
{
    
    // 初始化
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH / 20 + SCREEN_WIDTH / 10 + 64, SCREEN_WIDTH,SCREEN_HEIGHT) style:UITableViewStylePlain];
    
    // tag值
    self.tableView.tag = 100000;
    
    // 协议
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 不允许滚动
    self.tableView.scrollEnabled = NO;
    // 注册Cell
    [self.tableView registerClass:[LHSearchCell class] forCellReuseIdentifier:@"search"];
    
    // 添加并释放
    [self.view addSubview:self.tableView];

    
}

-(void)viewWillAppear:(BOOL)animated
{
    
    // 如果搜索框内容为空
    if (![self.searchBar.text isEqualToString:@""]) {
        
        // 搜索结果TableView隐藏
        self.tableView.hidden = YES;
        self.searchTableView.hidden = NO;
    } else {
        self.tabBarController.tabBar.hidden = YES;
        self.tableView.hidden = NO;
        self.searchTableView.hidden = YES;
    }
    
}
#pragma mark- 区数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // 区数
    if (tableView.tag == 100000) {
        return 2;
    } else {
        return self.searchDataArr.count;
    }
    
    
}

#pragma mark- 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        if (1 == indexPath.row) {
            return SCREEN_HEIGHT;
        } else {
            return SCREEN_WIDTH / 10;
        }
        
    } else {
        
        return 60;
        
    }
    
}

#pragma mark- 创建Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        if (0 == indexPath.row) {
            static NSString *str = @"qqq";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            }
            cell.textLabel.text = @"近期热点";
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } else {
            LHSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
            
            for (UIView *view in cell.contentView.subviews) {
                if (view) {
                    [view removeFromSuperview];
                }
            }
            
            cell.arr = self.hotSearchArr;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            return cell;
        }
    } else {
        
        static NSString *str1 = @"www";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str1];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str1];
        }
        LHSearchModel *model = [self.searchDataArr objectAtIndex:indexPath.row];
        
        NSString *str = model.title;
        
        // 去除无用字符
        str = [str stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
        
        // 获取搜索框内容
        NSRange rang = [str rangeOfString:self.searchBar.text];
        
        // 字体颜色
        cell.textLabel.textColor = [UIColor grayColor];
        
        // 获取高亮字符串
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str];
        
        // 高亮字体颜色
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rang];
        
        // 高亮字体
        cell.textLabel.attributedText = string;
        
        // 字体大小
        cell.textLabel.font = [UIFont systemFontOfSize:15 * ADAPT_FONT];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        [self.searchBar resignFirstResponder];
    } else {
        ZYDetailWebViewController *detail = [[ZYDetailWebViewController alloc] init];
        detail.docId = [_searchDataArr[indexPath.row] docid];
        [self.navigationController pushViewController:detail animated:YES];
        
    }
}

-(void)passValue:(NSString *)value
{
    
    self.searchBar.text = value;
    [self handleData];
    self.searchTableView.hidden = NO;
    self.tableView.hidden = YES;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    self.searchBar.text = searchText;
    if ([searchText isEqualToString:@""]) {
        self.tableView.hidden = NO;
        self.searchTableView.hidden = YES;
    } else {
        [self handleData];
        self.searchTableView.hidden = NO;
        self.tableView.hidden = YES;
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
